﻿// 项目：	Guan.CMS.Web - Guan.CMS
// 文件名：	NewsController.cs
// 
// 修改时间：2013-03-10 15:47
// 修改人：	Cooclsee

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using Guan.CMS.CommandProcessor.Dispatcher;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.Article;
using Guan.CMS.Model.Entities;
using Guan.CMS.Web.ViewModels.Article;
using PagedList;

namespace Guan.CMS.Web.Controllers
{
    public class NewsController : Controller
    {
        private readonly ICommandBus _commandBus;
        private readonly IArticleRepository _articleRepository;

        public NewsController(ICommandBus commandBus, IArticleRepository articleRepository)
        {
            this._commandBus = commandBus;
            this._articleRepository = articleRepository;
        }

        //
        // GET: /News/
        public ActionResult Index(int page = 1)
        {
            //找出所有新闻
            var newsList = _articleRepository.GetList(c => c.Category.Key=="news").OrderByDescending(c => c.UpdatedTime);
            const int pageSize = 5;
            var news = newsList.ToPagedList(page, pageSize);
            var viewList = Mapper.Map<IEnumerable<Article>, IEnumerable<ArticleSummaryViewModel>>(news);
            var newsList2 = new StaticPagedList<ArticleSummaryViewModel>(viewList, news.PageNumber, news.PageSize, news.TotalItemCount);
            return View(newsList2);
        }

        public ActionResult Detail(int id)
        {
            var blog = _articleRepository.GetById(id);
            if (blog != null && blog.IsPublished)
            {
                blog.Hits++; //点击数+1
                var command = new UpdateHitsCommand(blog.Id, blog.Hits);
                _commandBus.Submit(command);
                var viewModel = Mapper.Map<Article, ArticleDetailViewModel>(blog);
                return this.View(viewModel);
            }
            return Content("文章未找到");
        }

        public ActionResult List()
        {
            return RedirectToAction("Index");
        }
    }
}